package com.ruoyi.basic.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.basic.domain.TbExchangeRate;
import com.ruoyi.basic.mapper.TbExchangeRateMapper;
import com.ruoyi.basic.service.ITbExchangeRateService;
import com.ruoyi.common.enums.BizExceptionEnum;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;

/**
 * 汇率Service业务层处理
 * 
 * @author ruoyi
 * @date 2022-09-04
 */
@Service
public class TbExchangeRateServiceImpl extends ServiceImpl<TbExchangeRateMapper, TbExchangeRate> implements ITbExchangeRateService
{

    @Override
    public List<TbExchangeRate> listByCondition(TbExchangeRate tbExchangeRate) {
        return baseMapper.selectExchangeRateList(tbExchangeRate);
    }

    @Override
    public boolean deleteByIds(String ids) {
        if(ObjectUtils.isEmpty(ids)){
            throw new ServiceException(BizExceptionEnum.REQUEST_PARAMETER_ERROR.getMessage());
        }
        LambdaQueryWrapper<TbExchangeRate> wrapper = new LambdaQueryWrapper();
        wrapper.in(TbExchangeRate::getId, Arrays.asList(ids.split(",")));
        return remove(wrapper);
    }

    @Override
    public int saveRate(TbExchangeRate tbExchangeRate) {
        check(tbExchangeRate);
        return save(tbExchangeRate) ? 1 : 0;
    }

    private void check(TbExchangeRate tbExchangeRate) {
        LambdaQueryWrapper<TbExchangeRate> wrapper = new LambdaQueryWrapper();
        wrapper.eq(TbExchangeRate::getFrom, tbExchangeRate.getFrom())
                .eq(TbExchangeRate::getTo, tbExchangeRate.getTo())
                .apply(" date_format(rate_date,'%Y-%m-%d') = {0} ", DateUtils.parseDateToStr("yyyy-MM-dd",tbExchangeRate.getRateDate()))
                .orderByDesc(TbExchangeRate::getCreateTime);
        List<TbExchangeRate> list = list(wrapper);
        TbExchangeRate old = list.isEmpty() ? null : list.get(0);
        if (old != null && !old.getId().equals(tbExchangeRate.getId())) {
            throw new ServiceException("汇率已存在");
        }
    }

    @Override
    public int updateRate(TbExchangeRate tbExchangeRate) {
        check(tbExchangeRate);
        return updateById(tbExchangeRate) ? 1 : 0;
    }

    @Override
    public TbExchangeRate getByFromAndTo(String from, String to) {
        TbExchangeRate tbExchangeRate = getBaseMapper().selectByFromAndTo(from, to);
        if(null == tbExchangeRate){
            throw new ServiceException("未查询到汇率");
        }
        return tbExchangeRate;
    }
}
